import React, { useState, forwardRef, useContext} from "react";

import Form from '../../Form';
import { ScrollViewContext } from "../ScrollView";
import styles from './row.module.css';

function prop(object, propPath='') {
  const path = propPath.split('.').reverse();

  let curr = object;
  while(curr && path.length > 0) {
    curr = curr?.[path.pop()];
  }

  return curr;
}

const Cell = ({colName, data, type, width}) => {
  let displayedData;
  if (type === 'text') {
    displayedData = data;
  } else if (type === 'numeric') {
    displayedData = parseFloat(data).toLocaleString()
  } else {
    displayedData = data;
  }
  return <div key={colName} className={styles[`cell-${type}`]} type={type} style={{width}}>{displayedData ?? "\u200b"}</div>
}

const DisplayRow = (props) => {

  const {
    state,
    select,
    data:list,
    index,
    toggleEditing,
    editable=false,
    linkable=false
  } = props;

  const {
    disableScroll,
    scrollToItem
  } = useContext(ScrollViewContext);

  const data = list[index];

  const {schema, rowDisplayed} = state;

  const colElems = [];
  if (rowDisplayed !== undefined) {
    for (let colName of rowDisplayed) {
      const {type, width} = schema[colName];
      const widthConv = !isNaN(width) && width < 1 ? `${(width * 100).toFixed(2)}%` : width;
      colElems.push(<Cell {...{key:colName, colName, data:data[colName], type, width: widthConv}}/>);
    }
  } else {
    for (let [colName, entry] of Object.entries(schema)) {
      const {defaultValue, type, width} = entry;
      const widthConv = !isNaN(width) && width < 1 ? `${(width * 100).toFixed(2)}%` : width;
      colElems.push(<Cell {...{key:colName, colName, data:data[colName] ?? defaultValue, type, width: widthConv}}/>);
    }
  }

  const onDoubleClick = () => {
    if (editable) {
      toggleEditing(true);
      disableScroll();
      scrollToItem(index);
    }
  }

  const onClick = () => {
    if (linkable) {
      console.log('on click');
    } else {
      select({index});
    }
  }

  return <div onClick={onClick} onDoubleClick={onDoubleClick} className={styles['row']}>{colElems}</div>;
}

const Row = forwardRef((props, ref) => {

  const {
    correct,
    enableScroll,
    setEditable,
  } = useContext(ScrollViewContext);

  const {
    state,
    data,
    index,
    update,

    select,
    
    editable,
    linkable,

    // children,
    className,
    style,

  } = props;

  const [editing, setEditing] = useState(false);

  const toggleEditing = (cond) => {
    setEditing(cond);
    setEditable(!cond);
  }

  const onTrans = (data) => {
    const {'new-created-entry':_, ...currData} = data;
    console.log('curr data', currData);
    update({index}, currData);
    toggleEditing(false);
    correct({});
    enableScroll();
  }

  let content;
  if (!editing && !data[index]['new-created-entry']) {
    content = <DisplayRow {...{state, data, index, toggleEditing, select, editable, linkable}} />
  } else {
    content = <Form {...{className: styles['inline-form'], state, data: data[index], formType:'compact', onTrans}} />
  }

  return <div className={`${className} ${styles['container']}`} style={style}>
    <div className={styles['inner-wrapper']} ref={ref} data-index={index}>{content}</div>
  </div>

})

export default Row;